{% extends 'base.twig' %} 

{% block extraHead %} 
{{ parent() }}
<script type="text/javascript" src="{{ constant('CDN') }}/js/jquery.nestable.js"></script>
{% endblock %} 

{% block contentContainer %}
<div class="container">
	<div class="example" style="width: 100%;">
		<a href="{{ path('add-content', { modelName: 'Page', returnURL: returnURL|url_encode }) }}">
			<button class="button success">
				<i class="fa fa-plus-circle"></i>&nbsp;&nbsp;Add new page
			</button>
		</a>
		
		<div class="nestable-lists">
			<div class="dd" id="nestable">{{ tree|pages|raw }}</div>
		</div>
	</div>
</div>
{% endblock %} 

{% block extraFoot %}
<script>
	$(function() {
		$('#nestable').nestable().on('change', update);
		
		$('#nestable .delete').nestable().on('click', function(ev) {
			$this = $(this);
			$.Dialog({
				overlay: true,
				shadow: true,
				title: 'Confirm',
				width: 500,
				onShow: function(_dialog){
					var content = _dialog.children('.content').css('text-align', 'center');
					content.html(
						'<div style="padding-top: 20px;">Click OK to continue<div>' +
						'<div style="padding-top: 50px;">' +
							'<button class="button primary ok">OK</button>&nbsp;' +
							'<button class="button" onclick="$.Dialog.close();">Cancel</button>' +
						'</div>'
					);
					$('.window .content .ok').on('click', function() {
						$.Dialog.close();
						$.ajax({
							type : 'POST',
							url : '{{ path('remove-page') }}',
							data : 'id=' + $this.data('id') + '&modelName=Page',
							success : function(msg) { 
								location.reload(); 
							}
						});
					});
				}
			});
			return false;
		});
	});

	function update() {
		var root = {
			id : 0,
			children : $('#nestable').nestable('serialize'),
		}
		$.ajax({
			type : 'POST',
			url : '{{ path('sort-pages') }}',
			data : 'action=tree&data=' + encodeURIComponent(JSON.stringify(toArray(root))),
			success : function(msg) { }
		});
	};

	function toArray(node) {
		var result = [];
		for ( var idx in node.children) {
			var itm = node.children[idx];
			result.push({
				id : itm.id,
				parentId : node.id,
				rank : idx,
			});
			result = result.concat(toArray(itm));
		}
		return result;
	};
</script>
{% endblock %}

